'use client'

import { useState, useRef, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Label } from "@/components/ui/label"
import { Alert, AlertDescription } from "@/components/ui/alert"
import { IconEye, IconEyeOff, IconLock, IconUser, IconBuilding, IconCamera, IconUserCheck, IconChecklist, IconUserPlus, IconShield } from "@tabler/icons-react"
import Link from 'next/link'
import FaceRegister from '@/components/FaceRegister'
import useAuthStore from '@/stores/authStore'
import { LIVENESS_BASE_URL } from '@/lib/config'
import { api } from '@/lib/api'
import { PasswordCrypto } from '@/lib/crypto'
import { toast } from 'sonner'

export default function LoginPage() {
  const router = useRouter()
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)

  const [formData, setFormData] = useState({
    username: '',
    password: ''
  })
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')
  const [success, setSuccess] = useState('')
  const [showFaceRecognition, setShowFaceRecognition] = useState(false)
  const [isFaceRecognitionLoading, setIsFaceRecognitionLoading] = useState(false)
  const [stream, setStream] = useState<MediaStream | null>(null)
  // 活体认证相关
  const [livenessSteps, setLivenessSteps] = useState<string[]>([])
  const [currentLivenessIndex, setCurrentLivenessIndex] = useState(0)
  const [capturedImages, setCapturedImages] = useState<string[]>([])
  const [isLivenessVerifying, setIsLivenessVerifying] = useState(false)
  const [isLivenessRunning, setIsLivenessRunning] = useState(false)
  const [livenessError, setLivenessError] = useState('')
  const [showFaceRegister, setShowFaceRegister] = useState(false)
  const [token, setToken] = useState('')

  // 密码强度检查
  const [passwordStrength, setPasswordStrength] = useState<{
    strong: boolean
    score: number
    suggestions: string[]
  } | null>(null)

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({
      ...prev,
      [name]: value
    }))

    // 实时检查密码强度
    if (name === 'password' && value) {
      setPasswordStrength(PasswordCrypto.checkPasswordStrength(value))
    } else if (name === 'password' && !value) {
      setPasswordStrength(null)
    }

    // 清除错误信息
    if (error) setError('')
    if (success) setSuccess('')
  }

  // 启动摄像头
  const startCamera = async () => {
    try {
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: {
          width: 640,
          height: 480,
          facingMode: 'user'
        }
      })
      setStream(mediaStream)
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream
      }
    } catch (err) {
      setError('无法访问摄像头，请检查权限设置')
    }
  }

  // 停止摄像头
  const stopCamera = () => {
    if (stream) {
      stream.getTracks().forEach(track => track.stop())
      setStream(null)
    }
  }

  // 人脸检测
  const detectFace = async () => {
    if (!videoRef.current || !canvasRef.current) return false

    try {
      const canvas = canvasRef.current
      const video = videoRef.current
      const context = canvas.getContext('2d')

      if (!context) return false

      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      context.drawImage(video, 0, 0)

      // 调用后端人脸检测接口
      const imageBlob = await new Promise<Blob>((resolve) => {
        canvas.toBlob((blob) => resolve(blob!), 'image/jpeg', 0.9)
      })

      const formData = new FormData()
      formData.append('image', imageBlob, 'detect.jpg')

      const endpoint = LIVENESS_BASE_URL
      const response = await fetch(`${endpoint}/v1/face/detect`, {
        method: 'POST',
        body: formData
      })

      if (response.ok) {
        const result = await response.json()
        return result.success && result.face_count > 0
      }
      return false
    } catch (error) {
      console.error('人脸检测错误:', error)
      return false
    }
  }

  // 人脸识别验证
  const performFaceRecognition = async () => {
    if (!videoRef.current || !canvasRef.current) return

    setIsFaceRecognitionLoading(true)
    setError('')

    try {
      // 先检测是否有人脸
      const hasFace = await detectFace()
      if (!hasFace) {
        setError('未检测到人脸，请确保面部在识别框内')
        return
      }

      // 模拟识别处理时间
      await new Promise(resolve => setTimeout(resolve, 800))

      // 检测到人脸后，进入活体认证
      initLivenessSteps()
    } catch (err) {
      setError('人脸识别过程中出现错误')
    } finally {
      setIsFaceRecognitionLoading(false)
    }
  }

  // 初始化活体动作序列
  const initLivenessSteps = () => {
    const actions = ['请眨眼两次', '请向左转头', '请向右转头']
    setLivenessSteps(actions)
    setCurrentLivenessIndex(0)
    setCapturedImages([])
    setLivenessError('')
    // 自动开始流程
    runLivenessSequence(actions)
  }

  // 捕获当前帧
  const captureFrame = () => {
    if (!videoRef.current || !canvasRef.current) return null
    const canvas = canvasRef.current
    const video = videoRef.current
    const ctx = canvas.getContext('2d')
    if (!ctx) return null
    canvas.width = video.videoWidth
    canvas.height = video.videoHeight
    ctx.drawImage(video, 0, 0)
    return canvas.toDataURL('image/jpeg', 0.9)
  }

  // 确保视频就绪（loadedmetadata 且有尺寸）
  const waitForVideoReady = async (timeoutMs = 4000) => {
    const start = Date.now()
    while (true) {
      const v = videoRef.current
      if (v && v.videoWidth > 0 && v.videoHeight > 0 && v.readyState >= 2) return true
      if (Date.now() - start > timeoutMs) return false
      await new Promise(r => setTimeout(r, 100))
    }
  }

  // 自动执行活体动作序列：提示-等待-抓拍-下一步
  const runLivenessSequence = async (steps: string[]) => {
    try {
      setIsLivenessRunning(true)
      setLivenessError('')
      const ready = await waitForVideoReady()
      if (!ready) {
        setError('摄像头未就绪，请检查权限或网络后重试')
        setLivenessError('摄像头未就绪')
        return
      }
      const snapshots: string[] = []
      for (let i = 0; i < steps.length; i++) {
        setCurrentLivenessIndex(i)
        // 给用户0.8s阅读提示 + 1.2s执行动作
        await new Promise(r => setTimeout(r, 800))
        await new Promise(r => setTimeout(r, 1200))
        const img = captureFrame()
        if (img) snapshots.push(img)
      }
      setCapturedImages(snapshots)
      await verifyLiveness(snapshots)
    } finally {
      setIsLivenessRunning(false)
    }
  }

  // 重新识别：保留当前步骤列表，清空错误与抓拍，然后重新执行
  const restartLiveness = async () => {
    if (isLivenessRunning || isLivenessVerifying) return
    setLivenessError('')
    setCapturedImages([])
    setCurrentLivenessIndex(0)
    if (livenessSteps.length > 0) {
      await runLivenessSequence(livenessSteps)
    } else {
      initLivenessSteps()
    }
  }

  // 调用后端进行活体校验
  const verifyLiveness = async (images: string[]) => {
    try {
      setIsLivenessVerifying(true)
      setError('')
      const endpoint = LIVENESS_BASE_URL

      // 兼容你的后端：/api/ai/face/verify 需要 multipart 表单：user_id + file
      // 取第一张抓拍图作为验证图片
      const first = images?.[0]
      if (!first) throw new Error('未获取到抓拍图片')

      // dataURL 转 Blob
      const toBlob = async (dataUrl: string) => {
        const res = await fetch(dataUrl)
        return await res.blob()
      }
      const blob = await toBlob(first)
      const fd = new FormData()
      fd.append('user_id', formData.username)
      fd.append('file', blob, `${formData.username}.jpg`)

      // 修正验证API路径，与后端路由一致
      let verifyUrl = endpoint
      if (verifyUrl.endsWith('/')) {
        verifyUrl = verifyUrl.slice(0, -1)
      }
      verifyUrl = `${verifyUrl}/v1/face/verify`

      const res = await fetch(verifyUrl, { method: 'POST', body: fd })
      if (!res.ok) throw new Error('活体服务返回异常')
      const data = await res.json()
      const successVerify = data?.success === true
      if (successVerify) {
        setSuccess('活体认证通过，正在登录...')
        stopCamera()

        // 确保token已经设置到localStorage (在前面已经设置过，这里再次确认)
        const currentToken = useAuthStore.getState().token
        if (currentToken) {
          localStorage.setItem('token', currentToken)
          localStorage.setItem('auth_token', currentToken) // 保持兼容性
        }

        console.log('[认证调试] token设置成功，跳转到 /dashboard')
        router.push('/dashboard')
      } else {
        const errorMsg = data?.message || '活体认证未通过，请重试'
        setError(errorMsg)

        // 根据不同的错误类型设置不同的错误信息
        if (data?.code === 'NO_ENROLL' || data?.need_enroll) {
          setLivenessError('未找到该用户的人脸信息')
        } else if (data?.similarity && data.similarity < 0.5) {
          setLivenessError(`人脸不匹配 (相似度: ${data.similarity})`)
        } else {
          setLivenessError(errorMsg)
        }
      }
    } catch (e: any) {
      setError(e?.message || '活体认证服务异常，请稍后重试')
      setLivenessError('服务异常，请稍后重试')
    } finally {
      setIsLivenessVerifying(false)
    }
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()

    // 简单验证
    if (!formData.username || !formData.password) {
      setError('请输入用户名和密码')
      return
    }

    setIsLoading(true)
    setError('')
    setSuccess('')

    try {
      console.log('[登录调试] 开始登录流程，用户名:', formData.username)

      // 优先使用安全登录接口
      let response
      try {
        console.log('[登录调试] 尝试安全登录...')
        response = await api.auth.secureLogin({
          username: formData.username,
          password: formData.password
        })
        console.log('[登录调试] 安全登录成功，响应:', response)
        toast.success('安全登录成功！', {
          description: '密码已加密传输'
        })
      } catch (secureLoginError: any) {
        console.log('[登录调试] 安全登录失败，错误:', secureLoginError)
        console.log('[登录调试] 尝试普通登录...')

        // 安全登录失败，使用普通登录
        response = await api.auth.login({
          username: formData.username,
          password: formData.password
        })
        console.log('[登录调试] 普通登录成功，响应:', response)
        toast.success('登录成功！')
      }

      // 保存token和用户信息（统一使用token作为键名）
      localStorage.setItem('token', response.access_token)
      localStorage.setItem('auth_token', response.access_token) // 保持兼容性
      localStorage.setItem('user_info', JSON.stringify(response.user_info))

      // 使用store设置登录状态
      useAuthStore.getState().setLogin(response.access_token, {
        id: response.user_info.username,
        email: '',
        username: response.user_info.username,
        role: response.user_info.role
      })

      // 统一角色映射
      const roleMapping: { [k: string]: string } = {
        'admin': 'super_admin',
        'user': 'doctor',
        'manager': 'dean',
        'guide': 'nurse',
        'security': 'doctor'
      }
      const mappedRole = roleMapping[response.user_info.role] || response.user_info.role || 'doctor'

      // 更新用户信息中的角色
      response.user_info.role = mappedRole

      // 重新保存带有正确角色的用户信息
      localStorage.setItem('user_info', JSON.stringify(response.user_info))

      // 使用AuthManager保存完整的用户信息
      const { AuthManager } = await import('@/lib/users')
      const userObj = {
        id: response.user_info.username,
        username: response.user_info.username,
        password: '',
        name: response.user_info.username,
        role: mappedRole as any,
        email: '',
        phone: '',
        isActive: true,
        createdAt: new Date().toISOString()
      }
      AuthManager.login(userObj, response.access_token)

      // 如果是管理员，需要人脸验证
      if (mappedRole === 'super_admin') {
        // 检查是否已注册人脸
        const localRegistered = typeof window !== 'undefined' ?
          localStorage.getItem(`faceRegistered:${response.user_info.username}`) === 'true' : false

        if (!localRegistered) {
          setError('该管理员账号尚未录入人脸信息，请先完成人脸录入')
          setIsLoading(false)
          return
        }

        // 管理员登录成功，但需要人脸验证
        setSuccess('登录成功！请完成人脸验证...')
        setShowFaceRecognition(true)
        await startCamera()
      } else {
        // 普通用户直接登录
        setSuccess('登录成功！正在跳转...')

        // 跳转到首页或返回之前的页面
        const returnUrl = sessionStorage.getItem('return_url') || '/dashboard'
        sessionStorage.removeItem('return_url')
        router.push(returnUrl)
      }
    } catch (err: any) {
      console.error('登录失败:', err)

      let errorMessage = '登录失败，请稍后重试'
      if (err.response?.data?.detail) {
        errorMessage = err.response.data.detail
      } else if (err.response?.data?.message) {
        errorMessage = err.response.data.message
      } else if (err.message) {
        errorMessage = err.message
      }

      setError(errorMessage)
      toast.error('登录失败', {
        description: errorMessage
      })
    } finally {
      setIsLoading(false)
    }
  }

  // 处理人脸录入成功
  const handleFaceRegisterSuccess = () => {
    setShowFaceRegister(false)
    setSuccess('人脸录入成功！现在可以使用该账号登录')
    setError('')
  }

  // 处理人脸录入取消
  const handleFaceRegisterCancel = () => {
    setShowFaceRegister(false)
  }

  // 检查是否显示人脸录入按钮
  const shouldShowRegisterButton = () => {
    if (!formData.username) return false
    return typeof window !== 'undefined' ?
      localStorage.getItem(`faceRegistered:${formData.username}`) !== 'true' : false
  }

  // 组件卸载时清理摄像头
  useEffect(() => {
    return () => {
      stopCamera()
    }
  }, [])

  return (
    <div className="min-h-screen gradient-bg flex items-center justify-center p-4 sm:p-6 lg:p-8">
      <div className="w-full max-w-sm sm:max-w-md">
        {/* Logo 和标题 */}
        <div className="text-center mb-6 md:mb-8">
          <div className="flex flex-col sm:flex-row items-center justify-center gap-3 mb-4">
            <div className="w-14 h-14 sm:w-16 sm:h-16 bg-blue-100 rounded-xl flex items-center justify-center shadow-lg">
              <IconBuilding className="w-7 h-7 sm:w-8 sm:h-8 text-blue-600" />
            </div>
            <div className="text-center sm:text-left">
              <h1 className="text-xl sm:text-2xl font-bold text-gray-900 dark:text-gray-100">
                医疗空间数字孪生
              </h1>
              <p className="text-xs sm:text-sm text-gray-600 dark:text-gray-400">
                Medical Space Digital Twin
              </p>
            </div>
          </div>
        </div>

        {/* 登录表单 */}
        <Card className="glass-effect border border-white/20 dark:border-gray-700/20 shadow-xl">
          <CardHeader className="text-center pb-4">
            <CardTitle className="text-lg sm:text-xl font-semibold text-gray-900 dark:text-gray-100 flex items-center justify-center gap-2">
              <IconShield className="w-5 h-5 text-blue-600" />
              安全登录
            </CardTitle>
            <CardDescription className="text-sm sm:text-base text-gray-600 dark:text-gray-400">
              采用加密传输保护您的账号安全
            </CardDescription>
          </CardHeader>

          <CardContent className="space-y-4 sm:space-y-5 p-4 sm:p-6">
            <form onSubmit={handleSubmit} className="space-y-4">
              {/* 用户名 */}
              <div className="space-y-2">
                <Label htmlFor="username" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  用户名
                </Label>
                <div className="relative">
                  <IconUser className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="username"
                    name="username"
                    type="text"
                    value={formData.username}
                    onChange={handleInputChange}
                    placeholder="请输入用户名"
                    autoComplete="username"
                    className="pl-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                </div>
              </div>

              {/* 密码 */}
              <div className="space-y-2">
                <Label htmlFor="password" className="text-sm font-medium text-gray-700 dark:text-gray-300">
                  密码
                </Label>
                <div className="relative">
                  <IconLock className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                  <Input
                    id="password"
                    name="password"
                    type={showPassword ? 'text' : 'password'}
                    value={formData.password}
                    onChange={handleInputChange}
                    placeholder="请输入密码"
                    autoComplete="current-password"
                    className="pl-10 pr-10 bg-white/80 dark:bg-gray-800/80 border-gray-300 dark:border-gray-600 focus:ring-2 focus:ring-blue-500"
                    disabled={isLoading}
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300"
                    disabled={isLoading}
                  >
                    {showPassword ? (
                      <IconEye className="w-4 h-4" />
                    ) : (
                      <IconEyeOff className="w-4 h-4" />
                    )}
                  </button>
                </div>

                {/* 密码强度指示 */}
                {passwordStrength && (
                  <div className="mt-2 space-y-1">
                    <div className="flex items-center gap-2">
                      <div className="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-1">
                        <div
                          className={`h-1 rounded-full transition-all duration-300 ${passwordStrength.score <= 2 ? 'bg-red-500' :
                            passwordStrength.score <= 3 ? 'bg-yellow-500' :
                              'bg-green-500'
                            }`}
                          style={{ width: `${(passwordStrength.score / 5) * 100}%` }}
                        />
                      </div>
                      <span className={`text-xs ${passwordStrength.strong ? 'text-green-600 dark:text-green-400' :
                        'text-yellow-600 dark:text-yellow-400'
                        }`}>
                        {passwordStrength.strong ? '强' : '弱'}
                      </span>
                    </div>
                    {!passwordStrength.strong && passwordStrength.suggestions.length > 0 && (
                      <div className="text-xs text-gray-500 dark:text-gray-400">
                        建议：{passwordStrength.suggestions.slice(0, 2).join('、')}
                      </div>
                    )}
                  </div>
                )}
              </div>

              {/* 错误提示 */}
              {error && (
                <Alert variant="destructive" className="border-red-200 bg-red-50 dark:bg-red-900/20">
                  <AlertDescription className="text-red-700 dark:text-red-300 flex items-center justify-between gap-3">
                    <span>{error}</span>
                    {shouldShowRegisterButton() && error.includes('尚未录入人脸信息') && (
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() => setShowFaceRegister(true)}
                        className="text-red-700 dark:text-red-300 border-red-300 hover:bg-red-100 dark:hover:bg-red-900/30"
                      >
                        <IconUserPlus className="w-4 h-4 mr-1" />
                        立即录入
                      </Button>
                    )}
                  </AlertDescription>
                </Alert>
              )}

              {/* 成功提示 */}
              {success && (
                <Alert className="border-green-200 bg-green-50 dark:bg-green-900/20">
                  <AlertDescription className="text-green-700 dark:text-green-300">
                    {success}
                  </AlertDescription>
                </Alert>
              )}

              {/* 登录按钮 */}
              <Button
                type="submit"
                className="w-full h-10 sm:h-12 text-sm sm:text-base bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white font-medium rounded-lg shadow-lg hover:shadow-xl transition-all duration-200"
                disabled={isLoading}
              >
                {isLoading ? (
                  <div className="flex items-center space-x-2">
                    <span>验证中...</span>
                  </div>
                ) : (
                  <div className="flex items-center gap-2">
                    <IconShield className="w-4 h-4" />
                    安全登录
                  </div>
                )}
              </Button>
            </form>

            {/* 其他选项 */}
            <div className="flex items-center justify-between text-sm">
              <label className="flex items-center space-x-2 cursor-pointer">
                <input
                  type="checkbox"
                  className="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500"
                />
                <span className="text-gray-600 dark:text-gray-400">记住我</span>
              </label>
              <Link
                href="/forgot-password"
                className="text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300 transition-colors"
              >
                忘记密码？
              </Link>
            </div>

            {/* 测试账号信息 */}
            <div className="text-center pt-4 border-t border-gray-200 dark:border-gray-700">
              <p className="text-xs text-gray-500 dark:text-gray-400 mb-2">
                测试账号
              </p>
              <div className="space-y-1 text-xs text-gray-600 dark:text-gray-400">
                <p>超级管理员: jiangjiankai / jjk123456</p>
                <p>院长: guomengzhe / gmz123456</p>
                <p>主任: zhangyiwe / zyw123456</p>
                <p>医生: yaoyuan / yy123456</p>
                <p>护士: limengran / lmr123456</p>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 人脸识别模态框 */}
        {showFaceRecognition && (
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <Card className="w-full max-w-md glass-effect border border-white/20 dark:border-gray-700/20 shadow-2xl">
              <CardHeader className="text-center pb-4">
                <div className="flex items-center justify-center gap-2 mb-2">
                  <IconCamera className="w-6 h-6 text-blue-600" />
                  <CardTitle className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                    管理员身份验证
                  </CardTitle>
                </div>
                <CardDescription className="text-gray-600 dark:text-gray-400">
                  请先完成人脸识别，随后进行活体动作校验
                </CardDescription>
              </CardHeader>

              <CardContent className="space-y-4">
                {/* 摄像头预览 */}
                <div className="relative bg-gray-100 dark:bg-gray-800 rounded-lg overflow-hidden">
                  <video
                    ref={videoRef}
                    autoPlay
                    playsInline
                    muted
                    className="w-full h-64 object-cover"
                  />
                  <canvas
                    ref={canvasRef}
                    className="hidden"
                  />

                  {/* 识别框 */}
                  <div className="absolute inset-0 flex items-center justify-center">
                    <div className="w-48 h-48 border-2 border-blue-500 rounded-full opacity-50"></div>
                  </div>

                  {/* 状态指示 */}
                  <div className="absolute top-2 right-2">
                    <div className="flex items-center gap-1 bg-black/50 text-white px-2 py-1 rounded text-xs">
                      <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                      摄像头已启动
                    </div>
                  </div>
                </div>

                {/* 操作区：先人脸识别，后活体动作 */}
                <div className="space-y-3">
                  <div className="flex gap-3">
                    <Button
                      onClick={performFaceRecognition}
                      disabled={isFaceRecognitionLoading || livenessSteps.length > 0}
                      className="flex-1 bg-gradient-to-r from-blue-600 to-blue-700 hover:from-blue-700 hover:to-blue-800 text-white"
                    >
                      {isFaceRecognitionLoading ? (
                        <div className="flex items-center space-x-2">
                          <span>识别中...</span>
                        </div>
                      ) : (
                        <div className="flex items-center gap-2">
                          <IconUserCheck className="w-4 h-4" />
                          开始识别
                        </div>
                      )}
                    </Button>

                    <Button
                      variant="outline"
                      onClick={() => {
                        setShowFaceRecognition(false)
                        stopCamera()
                        setError('')
                        setSuccess('')
                        setLivenessSteps([])
                        setCapturedImages([])
                      }}
                      className="px-4"
                    >
                      取消
                    </Button>
                  </div>

                  {/* 活体动作步骤（全自动） */}
                  {livenessSteps.length > 0 && (
                    <div className="rounded-lg p-3 glass-effect border border-white/20 dark:border-gray-700/20">
                      <div className="flex items-center gap-2 mb-2 text-sm text-gray-600 dark:text-gray-300">
                        <IconChecklist className="w-4 h-4 text-blue-600" />
                        活体认证：系统将自动执行（共 {livenessSteps.length} 步）
                      </div>
                      <div className="flex items-center justify-between">
                        <div className="text-blue-600 dark:text-blue-400 font-medium">
                          第 {currentLivenessIndex + 1} 步：{livenessSteps[currentLivenessIndex]}
                        </div>
                        {livenessError ? (
                          <div className="text-xs text-red-600 dark:text-red-400">{livenessError}</div>
                        ) : (
                          <div className="text-center space-y-2">
                            <div className="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mx-auto">
                            </div>
                            <p className="text-sm text-gray-600">
                              {isLivenessRunning ? '自动抓拍中…' : '准备中…'}
                            </p>
                            <p className="text-xs text-gray-500">
                              步骤 {currentLivenessIndex + 1} / {livenessSteps.length}
                            </p>
                          </div>
                        )}
                      </div>
                      <div className="mt-2 text-xs text-gray-500 dark:text-gray-400 flex items-center justify-between">
                        <span>请按提示完成表情/动作</span>
                        <Button size="sm" variant="outline" className="h-7 px-2" onClick={restartLiveness} disabled={isLivenessRunning || isLivenessVerifying}>
                          重新识别
                        </Button>
                      </div>
                    </div>
                  )}

                  {isLivenessVerifying && (
                    <div className="text-center text-sm text-gray-600 dark:text-gray-300">正在验证活体，请稍候…</div>
                  )}
                </div>

                {/* 提示信息 */}
                <div className="text-center">
                  <p className="text-xs text-gray-500 dark:text-gray-400">
                    请将面部对准识别框，保持光线充足
                  </p>

                  {/* 识别失败时的处理选项 */}
                  {livenessError && (
                    <div className="mt-3 space-y-2">
                      {livenessError.includes('相似度') && (
                        <div className="p-2 bg-yellow-50 dark:bg-yellow-900/20 rounded text-xs">
                          <p className="text-yellow-700 dark:text-yellow-300 mb-2">
                            识别相似度较低，可能是光线或角度问题
                          </p>
                          <div className="flex gap-2 justify-center">
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={restartLiveness}
                              className="text-yellow-700 border-yellow-300 hover:bg-yellow-100"
                            >
                              重试验证
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setShowFaceRegister(true)}
                              className="text-blue-700 border-blue-300 hover:bg-blue-100"
                            >
                              重新录入
                            </Button>
                          </div>
                        </div>
                      )}

                      {livenessError.includes('未找到') && (
                        <div className="p-2 bg-red-50 dark:bg-red-900/20 rounded text-xs">
                          <p className="text-red-700 dark:text-red-300 mb-2">
                            未找到该用户的人脸信息
                          </p>
                          <Button
                            size="sm"
                            onClick={() => setShowFaceRegister(true)}
                            className="w-full bg-blue-600 hover:bg-blue-700 text-white"
                          >
                            <IconUserPlus className="w-4 h-4 mr-1" />
                            立即录入人脸
                          </Button>
                        </div>
                      )}
                    </div>
                  )}

                  {/* 通用录入入口 */}
                  {!livenessError && (
                    <div className="mt-3">
                      <Button
                        size="sm"
                        variant="ghost"
                        onClick={() => setShowFaceRegister(true)}
                        className="text-xs text-gray-500 hover:text-blue-600"
                      >
                        重新录入人脸信息
                      </Button>
                    </div>
                  )}
                </div>
              </CardContent>
            </Card>
          </div>
        )}

        {/* 人脸录入模态框 */}
        {showFaceRegister && (
          <div className="fixed inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50 p-4">
            <FaceRegister
              username={formData.username}
              onSuccess={handleFaceRegisterSuccess}
              onCancel={handleFaceRegisterCancel}
            />
          </div>
        )}
      </div>
    </div>
  )
}